package com.monster.servlet.detail;

import com.monster.pojo.Comment;
import com.monster.pojo.User;
import com.monster.service.InfoService;
import com.monster.service.InfoServiceImpl;
import com.monster.service.UserService;
import com.monster.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@WebServlet("/music/comment")
public class CommentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        InfoService is = new InfoServiceImpl();
        UserService us = new UserServiceImpl();
        String type = request.getParameter("type");
        Long id = Long.parseLong(request.getParameter("id"));
        ArrayList<Comment> commentList = is.selectCommentByTypeId(type, id);
        if (commentList.size() != 0) {
            Map<Comment, User> comments = new LinkedHashMap<>(commentList.size());
            for (Comment comm : commentList) {

                if (comm.getReplyId() != 0) {
                    User user = us.getUserById(is.getCommentByCommentId(comm.getReplyId()).getUser().getId());
                    comments.put(comm, user);
                } else {
                    comments.put(comm, null);
                }
            }
            request.setAttribute("comments", comments);
            request.getRequestDispatcher("comment.jsp").forward(request, response);
        } else {
            PrintWriter out = response.getWriter();
            out.print("no comment");
            out.flush();
            out.close();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
